<template>
  <TreeSelect
    v-model:value="selected"
    style="width: 100%"
    :tree-data="data"
    :treeCheckStrictly="treeCheckStrictly"
    tree-checkable
    allow-clear
    placeholder="请选择"
    tree-node-filter-prop="label"
    :fieldNames="fieldNames"
    :maxTagCount="0"
    @change="onSelected"
    :showCheckedStrategy="TreeSelect.SHOW_ALL"
    v-bind="$attrs"
    :maxTagPlaceholder="
      (omittedValues) => {
        if (omittedValues.length == 1) {
          return omittedValues[0].label;
        } else if (omittedValues.length == treeToArray(data).length) {
          return '全部';
        } else {
          return '多项目';
        }
      }
    "
  >
    <template #title="{ label, name, type }">
      <Tooltip>
        <template #title>
          {{ label || name }}
        </template>
        <div :class="{ label: true, type1: type == '1' }">
          {{ label || name }}
        </div>
      </Tooltip>
    </template>
  </TreeSelect>
</template>

<script setup lang="ts">
import { Ref, nextTick, onMounted, ref, watch } from 'vue';
import { Tooltip, TreeSelect } from 'ant-design-vue';
import { treeToArray } from '@/utils/utils';

const props = defineProps({
  formState: {
    type: Object,
    required: true,
  },
  data: {
    type: Array,
    default: () => [],
  },
  filed: {
    type: String,
    default: 'projectIds',
  },
  fieldNames: {
    type: Object,
    default: {
      children: 'children',
      label: 'label',
      key: 'id',
      value: 'id',
    },
  },
  treeCheckStrictly: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['change']);
const selected = ref([]);

watch(
  () => props.formState,
  (val: any) => {
    if (!val[props.filed]) selected.value = [];
  },
  { deep: true },
);

const onSelected = (values: any) => {
  console.log(values, 'valuesvalues');
  const value = props.treeCheckStrictly
    ? values.map((item: any) => item.value)
    : values;
  emit('change', value.join(','));
};
</script>

<style scoped>
.label {
  width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.type1 {
  color: #bababa;
}
:deep(.ant-select-selection-overflow-item) {
  max-width: 49% !important;
  margin-right: 4px !important;
}
</style>
